//
//  editYHQViewController.m
//  LazyCat
//
//  Created by rocky on 15/12/15.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "editYHQViewController.h"
#import "addYHQViewCell.h"
#import "sySheZhiController.h"
#import "AFNetworkHandler.h"
#import "FeWifiManHub.h"

@interface editYHQViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,backDelegate,UIAlertViewDelegate>
{
    FeWifiManHub *_loading;
}
@property (nonatomic,strong) UITableView *tableV;//
@property (nonatomic,strong) NSArray *dataArr;//第一列数组
@property (nonatomic,strong) NSArray *shezhiArr;//设置数组
@property (nonatomic,strong) NSArray *imgArr;//箭头图片数组
@property (nonatomic,strong) UIView *popView;//蒙板
@property (nonatomic,strong) UIView *timeView;//时间视图
@property (nonatomic,strong) UIDatePicker *datePicker;
@property (nonatomic,strong) NSString *one;//第一行
@property (nonatomic,strong) NSString *two;//第二行
@property (nonatomic,strong) NSString *three;//第三行
@property (nonatomic,strong) NSString *four;//第四行
@property (nonatomic,strong) NSString *five;//第五行
@property (nonatomic,strong) NSString *six;//第六行

@end

@implementation editYHQViewController

- (void)backAction:(UIButton *)btn {
    [self.view endEditing:YES];
    BOOL isEdit = [self.one isEqualToString:self.dict[@"title"]]
    && [self.two isEqualToString:self.dict[@"strc"]] && [self.three isEqualToString:self.dict[@"numtotal"]] && [self.four isEqualToString:self.dict[@"startdate"]] && [self.five isEqualToString:self.dict[@"expiredate"]] && [self.six isEqualToString:self.dict[@"min"]];
    if (isEdit) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"您的修改还未保存，返回后会丢失" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认返回", nil];
        [alert show];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        return;
    }
}
-(void)back:(NSString *)minMoney {//接收数据回来刷新该行
    self.six = minMoney;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:3];
    [self.tableV reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //添加导航栏与表视图
    [self initNav:@"编辑优惠券" doBack:YES];
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 63)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    lineV.alpha = 0.2;
    [self.navBar addSubview:lineV];
    self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64) style:UITableViewStyleGrouped];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableV registerClass:[addYHQViewCell class] forCellReuseIdentifier:@"Cell"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyboard:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tap.cancelsTouchesInView = NO;
    [self.tableV addGestureRecognizer:tap];
    [self.view addSubview:self.tableV];
    //添加数组
    self.dataArr = [NSArray array];
    self.shezhiArr = [NSArray array];
    self.imgArr = [NSArray array];
    self.dataArr = @[@[@"优惠券名称",@"面值"],@[@"发放总量"],@[@"生效时间",@"过期时间"],@[@"使用设置"]];
    self.shezhiArr = @[@[@"(新手券) 满49减5",@"未设置"],@[@"点击设置"],@[@"未设置",@"未设置"],@[@"已设置"]];
    self.imgArr = @[@[@"",@""],@[@""],@[@"",@""],@[@"huijiantou.png"]];
    //初始化第一次进来传的值 用于之后选择替换
    self.one = self.dict[@"title"];
    self.two = self.dict[@"strc"];
    self.three = self.dict[@"numtotal"];
    self.four = self.dict[@"startdate"];
    self.five = self.dict[@"expiredate"];
    self.six = self.dict[@"min"];
    
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {//隐藏键盘
    [self.view endEditing:YES];
}
-(void)hiddenKeyboard:(UITapGestureRecognizer *)tap {//隐藏键盘
    [self.view endEditing:YES];
}
//   datasource代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = self.dataArr[section];
    return arr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    addYHQViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.titleL.text = self.dataArr[indexPath.section][indexPath.row];
    cell.shezhiTextField.placeholder = self.shezhiArr[indexPath.section][indexPath.row];
    cell.arrImageV.image = [UIImage imageNamed:self.imgArr[indexPath.section][indexPath.row]];
    cell.shezhiTextField.delegate = self;
    cell.shezhiTextField.tag = indexPath.section*10+indexPath.row;
    if ([self.isFrom isEqualToString:@"no"]) {
        cell.shezhiTextField.userInteractionEnabled = NO;
    }else if ([self.isFrom isEqualToString:@"yes"]) {
        if (indexPath.section==self.dataArr.count-1 || indexPath.section==self.dataArr.count-2) {
            cell.shezhiTextField.userInteractionEnabled = NO;
        }
    }
    if (indexPath.section == 0 && indexPath.row == 0) {
        cell.shezhiTextField.textAlignment = NSTextAlignmentLeft;
    }else {
        cell.shezhiTextField.textAlignment = NSTextAlignmentRight;
    }
    if (indexPath.section == 0 && indexPath.row == 0) {//标题
        cell.shezhiTextField.text = [NSString stringWithFormat:@"%@",self.one];
    }else if (indexPath.section == 0 && indexPath.row == 1) {//面值
        float mianzhi = [self.two floatValue];
        cell.shezhiTextField.text = [NSString stringWithFormat:@"%.0f",mianzhi];
        cell.shezhiTextField.keyboardType = UIKeyboardTypeNumberPad;
    }else if (indexPath.section == 1 && indexPath.row == 0) {//总数量
        float allNum = [self.three floatValue];
        cell.shezhiTextField.text = [NSString stringWithFormat:@"%.0f",allNum];
        cell.shezhiTextField.keyboardType = UIKeyboardTypeNumberPad;
    }else if (indexPath.section == 2 && indexPath.row == 0) {//起始日期
        cell.shezhiTextField.text = [NSString stringWithFormat:@"%@",self.four];
    }else if (indexPath.section == 2 && indexPath.row == 1) {//截止日期
        cell.shezhiTextField.text = [NSString stringWithFormat:@"%@",self.five];
    }else if (indexPath.section == 3 && indexPath.row == 0) {
        if (self.six.length == 0) {
            cell.shezhiTextField.text = @"未设置";
        }else {
            cell.shezhiTextField.text = @"已设置";
        }
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {//表视图点击方法
    if (indexPath.section==self.dataArr.count-1) {
        sySheZhiController *sySetVC = [[sySheZhiController alloc]init];
        sySetVC.delegate = self;
        sySetVC.isFrom = @"1";
        if ([self.isFrom isEqualToString:@"yes"]) {
            sySetVC.isEdit = @"yes";
        }else if ([self.isFrom isEqualToString:@"no"]) {
            sySetVC.isEdit = @"no";
        }
        sySetVC.money = self.six;
        [self.navigationController pushViewController:sySetVC animated:YES];
    }else if (indexPath.section == 2) {
        if ([self.isFrom isEqualToString:@"no"]) {
            
        }else if ([self.isFrom isEqualToString:@"yes"]) {
            [self upTimeView:indexPath.row];//点击出现时间view
        }
    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 0) {//标题
        self.one = [NSString stringWithFormat:@"%@",textField.text];
    }else if (textField.tag == 1) {//面值
        self.two = [NSString stringWithFormat:@"%@",textField.text];
    }else if (textField.tag == 10) {//发放总量
        self.three = [NSString stringWithFormat:@"%@",textField.text];
    }else if (textField.tag == 20) {
        self.four = [NSString stringWithFormat:@"%@",textField.text];
    }else if (textField.tag == 21) {
        self.five = [NSString stringWithFormat:@"%@",textField.text];
    }else if (textField.tag == 30) {
        self.six = [NSString stringWithFormat:@"%@",textField.text];
    }
}
-(void)upTimeView:(NSInteger)row {//点击出现时间view
    [self.view endEditing:YES];
    UIWindow *keyWindow=[UIApplication sharedApplication].keyWindow;
    self.popView=[[UIView alloc]initWithFrame:keyWindow.bounds];
    self.popView.backgroundColor=SetColor(0, 0, 0, .4);
    self.popView.alpha=0;
    [keyWindow addSubview:self.popView];
    [UIView animateWithDuration:0.2 animations:^{
        self.popView.alpha=1;
    }];
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidentPopView)];
    [self.popView addGestureRecognizer:tap];
    //添加时间view
    self.timeView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight, ScreenWidth, 200)];
    self.timeView.backgroundColor = [UIColor whiteColor];
    [keyWindow addSubview:self.timeView];
    //地址view上面的东西
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 45)];
    backView.backgroundColor = [UIColor whiteColor];
    [self.timeView addSubview:backView];
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(0, 0, 60, 45);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(hidentPopView) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [backView addSubview:cancelBtn];
    UILabel *label = [[UILabel alloc]init];
    if (row == 0) {
        label.text = @"选择上班时间";
    }else {
        label.text = @"选择下班时间";
    }
    label.hidden = YES;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor darkGrayColor];
    label.font = [UIFont systemFontOfSize:14];
    label.frame = CGRectMake(60, 0, ScreenWidth-120, 45);
    [backView addSubview:label];
    UIButton *qdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    qdBtn.frame = CGRectMake(ScreenWidth-60, 0, 60, 45);
    [qdBtn setTitle:@"确定" forState:UIControlStateNormal];
    [qdBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    qdBtn.tag = row;
    [qdBtn addTarget:self action:@selector(clickSuccess:) forControlEvents:UIControlEventTouchUpInside];
    qdBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [backView addSubview:qdBtn];
    self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 45, ScreenWidth, 155)];
    self.datePicker.backgroundColor = BackColor;
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    [self.timeView addSubview:self.datePicker];
    //点击视图出来
    CGPoint center = self.timeView.center;
    center.y = ScreenHeight-100;
    [UIView animateWithDuration:0.2 animations:^{
        //设置要被动画的那个视图
        //在动画结束时，它的属性处于什么状态
        self.timeView.center = center;
    }];
}
-(void)clickSuccess:(UIButton *)sender {//点击成功之后的事件
    NSDate *select  = [self.datePicker date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dT = [dateFormatter stringFromDate:select];
    NSLog(@"%@",dT);
    if (sender.tag == 0) {
        self.four = dT;
    }else {
        self.five = dT;
    }
    CGPoint center = self.timeView.center;//隐藏视图
    center.y = ScreenHeight+100;
    [UIView animateWithDuration:0.2 animations:^{
        self.timeView.center = center;
        self.popView.alpha=0;
    }];//刷新某一行
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:sender.tag inSection:2];
    [self.tableV reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}
-(void)hidentPopView {//隐藏视图
    CGPoint center = self.timeView.center;
    center.y = ScreenHeight+100;
    [UIView animateWithDuration:0.2 animations:^{
        self.timeView.center = center;
        self.popView.alpha=0;
    }];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {//分区头部高度
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {//分区尾部高度
    if (section==self.dataArr.count-1) {
        return 150;
    }else {
        return 0.01;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {//添加底部视图
    if ([self.isFrom isEqualToString:@"no"]) {
        return nil;
    }else {
        if (section==self.dataArr.count-1) {
            UIView *footerV = [[UIView alloc]init];
            UIButton *bcBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            bcBtn.frame = CGRectMake(20, 20, ScreenWidth-40, 50);
            bcBtn.layer.cornerRadius = 5.0;
            bcBtn.layer.masksToBounds = YES;
            bcBtn.backgroundColor = MainColor;
            [bcBtn setTitle:@"保存" forState:UIControlStateNormal];
            bcBtn.titleLabel.font = [UIFont systemFontOfSize:17];
            [bcBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [bcBtn addTarget:self action:@selector(baocun) forControlEvents:UIControlEventTouchUpInside];//保存点击方法
            [footerV addSubview:bcBtn];
            UIButton *sxBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            sxBtn.frame = CGRectMake(20, 80, ScreenWidth-40, 50);
            sxBtn.layer.cornerRadius = 5.0;
            sxBtn.layer.borderColor = MainColor.CGColor;
            sxBtn.layer.borderWidth = 1.0;
            sxBtn.layer.masksToBounds = YES;
            sxBtn.backgroundColor = [UIColor whiteColor];
            [sxBtn setTitle:@"使失效" forState:UIControlStateNormal];
            sxBtn.titleLabel.font = [UIFont systemFontOfSize:17];
            [sxBtn setTitleColor:MainColor forState:UIControlStateNormal];
            [sxBtn addTarget:self action:@selector(shixiao) forControlEvents:UIControlEventTouchUpInside];//失效点击方法
            [footerV addSubview:sxBtn];
            return footerV;
        }else{
            return nil;
        }
    }
}
-(void)baocun {//保存点击方法
    [self.view endEditing:YES];
    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
    [self.view addSubview:_loading];
    [_loading show];//loading框出现
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"网络不给力"];
        [_loading dismiss];
        [_loading removeFromSuperview];
    }
    NSString *url = [NSString stringWithFormat:saveYHQUrl,self.dict[@"couponxpostrecordid"],self.one,self.two,self.four,self.five,self.six,self.three];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dictt = result;
        NSString *r = dictt[@"r"];
        if ([r isEqualToString:@"T"]) {
            [AppData share].isLoadd = YES;
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [[MessShowView share] showWithMess:dictt[@"m"] login:NO];
        }
        [_loading dismiss];
        [_loading removeFromSuperview];
    }];
    [_loading dismiss];
    [_loading removeFromSuperview];
}
-(void)shixiao {//失效点击方法
    [self.view endEditing:YES];
    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
    [self.view addSubview:_loading];
    [_loading show];//loading框出现
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"网络不给力"];
        [_loading dismiss];
        [_loading removeFromSuperview];
    }
    NSString *url = [NSString stringWithFormat:noSaveYHQUrl,self.dict[@"couponxpostrecordid"],@"0"];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dictt = result;
        NSString *r = dictt[@"r"];
        if ([r isEqualToString:@"T"]) {
            [AppData share].isLoadd = YES;
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [[MessShowView share] showWithMess:dictt[@"m"] login:NO];
        }
        [_loading dismiss];
        [_loading removeFromSuperview];
    }];
    [_loading dismiss];
    [_loading removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
